package com.aso114.project.mvp.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aso114.project.R;
import com.aso114.project.adapter.SelectedTopicPayAdapter;
import com.aso114.project.base.BaseSimpleActivity;
import com.aso114.project.bean.JingPinBean;
import com.aso114.project.bean.PayNumBean;
import com.aso114.project.bean.PriceListBean;
import com.aso114.project.dialog.PayDialog;
import com.aso114.project.mvp.alipay.H5PayDemoActivity;
import com.aso114.project.mvp.model.CallBack;
import com.aso114.project.mvp.model.CommentModel;
import com.aso114.project.util.ActivityCollector;
import com.aso114.project.util.Helper;
import com.aso114.project.util.SystemBarHelper;
import com.aso114.project.util.ToastUtils;
import com.aso114.project.util.WxpayUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class SelectedTopicPayActivity extends BaseSimpleActivity implements SelectedTopicPayAdapter.OnItemClickListener {
    @BindView(R.id.layout_title_bar_back_iv)
    ImageView layoutTitleBarBackIv;
    @BindView(R.id.layout_title_bar_title_tv)
    TextView layoutTitleBarTitleTv;
    @BindView(R.id.layout_title_bar_right_iv)
    ImageView layoutTitleBarRightIv;
    @BindView(R.id.layout_title_bar_right_tv)
    TextView layoutTitleBarRightTv;
    @BindView(R.id.title_top_ly)
    RelativeLayout titleTopLy;
    @BindView(R.id.pay_listView)
    RecyclerView payListView;
    @BindView(R.id.pay_money)
    TextView payMoney;
    @BindView(R.id.pay_btn)
    TextView payBtn;
    @BindView(R.id.pay_check)
    TextView payCheck;
    @BindView(R.id.pay_protocol)
    TextView payProtocol;
    Dialog dialog;
    SelectedTopicPayAdapter selectedTopicPayAdapter;
    private boolean isCheck;// checkbox 点击状态
    private boolean isClick;// 支付是否可点击
    private ArrayList<JingPinBean> bean = new ArrayList<>();
    private double payPrice = 0.00;

    public static void statIntent(Context context) {
        Intent intent = new Intent(context, SelectedTopicPayActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected int getResouseId() {
        return R.layout.activity_selected_topic_pay;
    }

    @Override
    protected void initView() {
        SystemBarHelper.immersiveStatusBar(this);
        SystemBarHelper.setHeightAndPadding(this, titleTopLy);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            SystemBarHelper.immersiveStatusBar(this, 0);
            SystemBarHelper.setStatusBarDarkMode(this);
        }
        layoutTitleBarTitleTv.setText("精选题库");

        PayDialog dialog = new PayDialog(this,null, new PayDialog.OnDialogClick() {
            @Override
            public void onZfb(PriceListBean bean) {
                payData("1");
            }

            @Override
            public void onWx(PriceListBean bean) {

                if(Helper.isWeixinAvilible(SelectedTopicPayActivity.this)==true){
                    payData("2");
                }else {
                    Helper.showToast("您未安装微信,不能使用微信支付");
                }
            }
        });
        dialog.show();

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        //设置布局管理器
        payListView.setLayoutManager(layoutManager);
        selectedTopicPayAdapter = new SelectedTopicPayAdapter(this);
        payListView.setAdapter(selectedTopicPayAdapter);
        getData();
        selectedTopicPayAdapter.setOnItemClickListener(this);
    }

    private void getData() {
        CommentModel.getInstant().getJingPin(new CallBack() {
            @Override
            public void onSuccess(Object o, boolean isSuccess, String msg) {
                bean = (ArrayList<JingPinBean>) o;
                if (bean == null || bean.isEmpty()) {
                    return;
                }
                selectedTopicPayAdapter.setData(bean);
                selectedTopicPayAdapter.notifyDataSetChanged();
            }

            @Override
            public void onFailure(String fail) {

            }
        });
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void getBroadcast(Context context, Intent intent) {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }


    private void payData(final  String payType) {


        View dialogview = SelectedTopicPayActivity.this.getLayoutInflater().inflate(
                R.layout.loading_view, null);
        dialog = new Dialog(SelectedTopicPayActivity.this, R.style.dialogStyle);
        dialog.setContentView(dialogview, new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        dialog.getWindow().setGravity(Gravity.CENTER);
        // 设置点击外围解散
        dialog.setCanceledOnTouchOutside(true);
        dialog.setCancelable(true);//设置是否可以按退回键取消
        dialog.show();

        CommentModel.getInstant().setCreate(payType,  "4", new CallBack() {
            @Override
            public void onSuccess(Object o, boolean isSuccess, String msg) {
                Helper.gotoLogin(isSuccess);//token失效去重新登陆

                dialog.cancel();
                PayNumBean payNumBean = (PayNumBean) o;
                if (payNumBean==null){
                    return;
                }

                if(payType.equals("1")){
                    Intent intent = new Intent(SelectedTopicPayActivity.this, H5PayDemoActivity.class);
                    intent.putExtra("orderNo", payNumBean.getOrderNo());
                    startActivity(intent);
                }
                if(payType.equals("2")){

                    Intent intent = new Intent(SelectedTopicPayActivity.this, WxPayOrderActivity.class);
                    intent.putExtra("orderNo", payNumBean.getOrderNo());
                    startActivity(intent);
                }
            }

            @Override
            public void onFailure(String fail) {
                dialog.cancel();
            }
        });
    }


    @OnClick({R.id.layout_title_bar_back_iv, R.id.pay_btn, R.id.pay_check, R.id.pay_protocol})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_title_bar_back_iv:
                finish();
                break;
            case R.id.pay_btn:
                if (isClick) {
                    PayDialog dialog = new PayDialog(this,null, new PayDialog.OnDialogClick() {

                        @Override
                        public void onZfb(PriceListBean bean) {
                            payData("1");
                        }

                        @Override
                        public void onWx(PriceListBean bean) {

                            if(Helper.isWeixinAvilible(SelectedTopicPayActivity.this)==true){
                            payData("2");
                            }else {
                                Helper.showToast("您未安装微信,不能使用微信支付");
                            }
                        }
                    });
                    dialog.show();
                }
                break;
            case R.id.pay_check:
                if (isCheck) {
                    Drawable drawableLeft = getResources().getDrawable(
                            R.mipmap.buy_xy1_ic);
                    payCheck.setCompoundDrawablesWithIntrinsicBounds(drawableLeft, null, null, null);
                    isCheck = false;
                    payBtn.setBackgroundResource(R.color.aff6559_60);
                    isClick = false;
                } else {
                    Drawable drawableLeft = getResources().getDrawable(
                            R.mipmap.buy_xy2_ic);
                    payCheck.setCompoundDrawablesWithIntrinsicBounds(drawableLeft, null, null, null);
                    isCheck = true;
                    if (select()) {
                        payBtn.setBackgroundResource(R.color.aff6559);
                        payBtn.setTextColor(getResources().getColor(R.color.white));
                        isClick = true;
                    } else {
                        payBtn.setBackgroundResource(R.color.aff6559_60);
                        payBtn.setTextColor(getResources().getColor(R.color.white_60));
                        isClick = false;
                    }
                }
                break;
            case R.id.pay_protocol:
                Intent intent = new Intent(this, NeedNoticeDetailActivity.class);
                intent.putExtra("type", "112");
                startActivity(intent);
                break;
        }
    }

    @Override
    public void onItemClick() {  // adapter 选中点击
        if (select()) {
            payBtn.setBackgroundResource(R.color.aff6559);
            payBtn.setTextColor(getResources().getColor(R.color.white));
            isClick = true;
        } else {
            payBtn.setBackgroundResource(R.color.aff6559_60);
            payBtn.setTextColor(getResources().getColor(R.color.white_60));
            isClick = false;
        }
        payMoney.setText("合计：￥" + String.format("%.2f", getPrice()));
    }

    private boolean select() {
        for (int i = 0; i < bean.size(); i++) {
            if (bean.get(i).isSelect()) {
                if (isCheck) {
                    return true;
                }
            }
        }
        return false;
    }


    private double getPrice() {
        payPrice = 0;
        for (int i = 0; i < bean.size(); i++) {
            if (bean.get(i).isSelect()) {
                payPrice += bean.get(i).getOnePrice();

            }
        }
        return payPrice;
    }

    private JSONArray getJingPinId() {
        JSONArray Array = new JSONArray();
        for (int i = 0; i < bean.size(); i++) {
            if (bean.get(i).isSelect()) {
                JSONObject stoneObject = new JSONObject();
                try {
                    stoneObject.put("JingPinId", bean.get(i).getJingPinId());
                    Array.put(stoneObject);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
        return Array;
    }

}
